package by.grsu.na.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.na.entity.Product;
import by.grsu.na.table.ProductTable;

import com.epam.grsulab.webapi.dao.AbstractDao;


public class ProductDao extends AbstractDao<ProductTable, Product> {

	public ProductDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Product newProduct) {

		newProduct.setId(getNextId());

		final ProductTable productTable = deserializeFromXml();

		productTable.getRows().add(newProduct);

		serializeToXml(productTable);
	}

	@Override
	public void update(final Product entity) {

		final ProductTable productTable = deserializeFromXml();

		for (final Product row : productTable.getRows()) {
			if (row.getId().equals(entity.getId())) {

				
				row.setType(entity.getType());
				row.setCost(entity.getCost());
				break;
			}
		}

		serializeToXml(productTable);
	}

	@Override
	public Product get(final Serializable id) {

		final ProductTable productTable = deserializeFromXml();

		for (final Product row : productTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Product> getAll() {

		final ProductTable productTable = deserializeFromXml();
		return productTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {

		final ProductTable productTable = deserializeFromXml();

		Product toBeDeleted = null;
		for (final Product row : productTable.getRows()) {
			if (row.getId().equals(id)) {

				toBeDeleted = row;
				break;
			}
		}

		productTable.getRows().remove(toBeDeleted);

		serializeToXml(productTable);
	}

	@Override
	protected Class<ProductTable> getTableClass() {
		return ProductTable.class;
	}

}
